/*
 * Copyright 2007 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.neusoft.wenjoy.core;

import java.io.File;
import java.util.HashSet;
import java.util.Properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.PropertyValue;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.neusoft.wenjoy.bootstrap.BeanFactory;

/**
 *-HOME_DIR 
 * -bin 
 * -conf 
 *  -db.properties
 *  -log.properties 
 *  -... 
 * -lib 
 *  -class12.jar
 *  -... 
 * -plugins
 *  -com.neusoft.wenjoy.core_1.0
 *  -... 
 * -logs
 * 
 * @author vvenli@gmail.com
 * 
 */
public class PluginBeanFactory implements BeanFactory {
	private String home = null;
	private ClassPathXmlApplicationContext factory = null;

	protected final Log logger = LogFactory.getLog(getClass());

	public PluginBeanFactory(String homedir) {
		Thread.currentThread().setContextClassLoader(
				this.getClass().getClassLoader());
		this.home = homedir;
		HashSet list = new PluginDirectory(homedir).getConfigLocations();
		System.out.println(list);
		
		factory = new ClassPathXmlApplicationContext((String[]) list
				.toArray(new String[list.toArray().length]));
		
		setDefaultProperties();
		factory.refresh();
		
		postProcessBeanFactory(factory.getBeanFactory());
	}

	public void postProcessBeanFactory(
			ConfigurableListableBeanFactory beanFactory){
		String[] beanNames = beanFactory.getBeanDefinitionNames();
		for (int i = 0; i < beanNames.length; i++) {
			BeanDefinition bd = beanFactory.getBeanDefinition(beanNames[i]);
			MutablePropertyValues propValues = bd.getPropertyValues();

			PropertyValue[] pvs = propValues.getPropertyValues();
			
			if( logger.isDebugEnabled() ){
				for(int j = 0; j < pvs.length; j++){
					logger.debug( pvs[j].getValue() );
				}
			}
		}
	}
	
	private void setDefaultProperties(){
		PropertyPlaceholderConfigurer cfg = new PropertyPlaceholderConfigurer();
		Properties props = new Properties();
		props.setProperty("com.neusoft.wenjoy.home", this.home);
		cfg.setProperties(props);
		factory.addBeanFactoryPostProcessor(cfg);		
	}

	public Object getBean(String name) {
		return factory.getBean(name);
	}
	
    private class PluginDirectory {
    	private HashSet list = new HashSet();

    	public PluginDirectory(String homedir) {
    		getConfigLocations(homedir);
    	}

    	public HashSet getConfigLocations() {
    		return list;
    	}

    	private void getConfigLocations(String homedir) {
    		File home = new File(homedir + "/plugins");

    		String[] plugins = home.list();
    		for (int i = 0; i < plugins.length; i++) {
    			String loc = getPackageName(plugins[i]);
    			list.add("/" + loc + "/main.xml");
    			list.add(loc + "/plugin.xml");
    		}
    	}

    	private String getPackageName(String dirname) {
    		if( dirname.indexOf("_") > 0 ){
    			return dirname.substring(0, dirname.indexOf("_")).replace('.', '/');
    		}else{
    			return dirname;
    		}
    	}
    }
}
